#coding=utf-8
'''
Created on 2017-7-15

@author: zhangyadong
'''

import Table
import time
import logging
from pycommon import Const
from twisted.internet import task
import random

class BlackUser(object):
    def __init__(self,uid,tableId):
        self.uid = uid
        self.tableId = tableId
        self.time = time.time()


class TableManager(object):
    def __init__(self):
        self.tables = {}
        self.users = {}
        self.kickedUsers = {}

    def start(self):
        l = task.LoopingCall(self.onTimer)
        l.start(1, False)

    def onTimer(self):
        self.doTask()
    
    def doTask(self):
        remove = []
        for tableId in self.kickedUsers:
            buList = self.kickedUsers[tableId]
            for i in range(len(buList) - 1,-1,-1):
                bu = buList[i]
                if time.time() - bu.time >= 120:
                    buList.remove(bu)
                    logging.debug(u"remove uid=%d from blackRoom tableId=%s",bu.uid,bu.tableId)

    def create6SNum(self):
        strNum = ""
        while True:
            nums = []
            for i in range(6):
                nums.append(str(random.randint(0,9)))
            key = "".join(nums)
            if self.tables.get(key,None) == None:
                strNum = key
                break
        return strNum
        

    def createTable(self,tableIdStr):
        t = Table.Table();
        self.tables[tableIdStr] = t

    def initTable(self,userId,tableId,gameIp,gamePort,maxRound,tableModel,playModel,cardId,cardNum,hallId,tableIdStr):
        t = self.tables.get(tableIdStr)
        t.createTable(userId,tableId,gameIp,gamePort,maxRound,tableModel,playModel,cardId,cardNum,hallId)
        logging.debug(u"tablemanager createTable sucess tableId = %d",tableId)


    def getTableByTableIdStr(self,tableIdStr):
        t = self.tables.get(tableIdStr,None)
        return t

    def canEnterTable(self,tableIdStr,userId):
        if self.userIsInTable(userId):
            return Const.ERR_MJ_USER_HASINTABLE
        table = self.getTableByTableIdStr(tableIdStr)
        if table == None:
            return Const.ERR_MJ_TABLE_NOTEXIT
        else:
            users = table.users
            if len(users) >= table.tableModel:
                return Const.ERR_MJ_TABLE_ISFULL
            
        k = self.kickedUsers.get(tableIdStr,None)
        if k != None:
            for black in k:
                if black.uid == userId:
                    logging.debug(u"uid=%d has kicked",userId)
                    return Const.ERR_MJ_PLAYER_IN_KICK
        return Const.ERR_OK

    def enterTable(self,tableIdStr,userId):
        table = self.getTableByTableIdStr(tableIdStr)
        self.users[userId] = tableIdStr
        table.userEnterTable(userId)
        return table

    def leaveTable(self,uid):
        tableIdstr = self.users.get(uid,"")
        table = self.tables.get(tableIdstr,None)
        if table == None:
            logging.debug("uid=%d leaveTable tableIdstr = %s and table==None",uid,tableIdstr)
        else:
            logging.debug(u'uid=%d leaveTable tableIdstr = %s',uid,tableIdstr)
            self.users.pop(uid)
            table.userLeaveTable(uid)
            lastUsers = table.getUsers()
            if len(lastUsers) == 0:
                self.tables.pop(tableIdstr)
                logging.debug("tableIdstr = %s persons all Leaved",tableIdstr)
            else:
                logging.debug("tableIdstr = %s lastUserId = [%s]",tableIdstr,str(lastUsers))

        
    
    def dismissTable(self,tableIdStr,ownerId):
        logging.debug("uid=%d request dismissTable=%s",ownerId,tableIdStr)
        code = Const.ERR_OK
        table = self.getTableByTableIdStr(tableIdStr)
        if table and table.ownerId == ownerId:
            #self.leaveTable(ownerId)
            pass
        else:
            code = Const.ERR_MJ_DISBAND_TABLE_ERROR
        return code
    
    def kickUser(self,tableIdStr,userId):
        logging.debug(u"uid=%d has be kicked tableIdStr=%s",userId,tableIdStr)
        bu = BlackUser(userId,tableIdStr)
        if self.kickedUsers.get(tableIdStr,None) == None:
            self.kickedUsers[tableIdStr] = []
        self.kickedUsers[tableIdStr].append(bu)

        #房主踢出玩家 会发logout
        #table = self.getTableByTableIdStr(tableIdStr)
        #self.leaveTable(table,userId)
    
    def userIsInTable(self,uid):
        return self.users.get(uid,None) != None

    def getTableByUid(self,uid):
        tableIdstr = self.users.get(uid,"")
        table = self.tables.get(tableIdstr,None)
        return table

    def checkKickUser(self,tableIdStr,uid):
        if tableIdStr != "":
            return self.users.get(uid,"") == tableIdStr
        return False
        
    def userLogoutGame(self,uid):
        logging.debug(u"###########userLogoutGame############## uid=%d",uid);
        self.leaveTable(uid)


instance = TableManager()